package com.bruce.controller;

import com.bruce.Common.Result;
import com.bruce.Common.Resultcode;
import com.bruce.bean.Course;
import com.bruce.bean.Courseplan;
import com.bruce.bean.Dto.CourseplanDto;
import com.bruce.bean.Dto.GradeDto;
import com.bruce.bean.Student;
import com.bruce.bean.Teacher;
import com.bruce.service.CourseService;
import com.bruce.service.StudentService;
import com.bruce.service.TeacherService;
import com.bruce.service.impl.CourseServiceImpl;
import com.bruce.service.impl.StudentServiceImpl;
import com.bruce.service.impl.TeacherServiceImpl;
import com.bruce.utils.PageUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 学生控制器
 */
@WebServlet("/studentServlet.do")
public class StudentServlet extends HttpServlet {

    StudentService studentService=new StudentServiceImpl();
    CourseService courseService = new CourseServiceImpl();
    TeacherService teacherService  = new TeacherServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        String method = req.getParameter("flag");
        HttpSession session = req.getSession();
        String syscode=(String) session.getAttribute("syscode"); //系统生成验证码
        switch (method){
            case "login":
                student_login(req, resp, session, syscode);
                break;
            case "logout":
                student_logout(resp, session);
                break;
            case "addStudent":
                Result result = add_user(req);
                resp.getWriter().write("<script>alert('学生课程成功');location.href='/admin/addStudent.jsp';</script>");
                break;
            case "selectCourseList":
                FindAllCourse(req, resp);
                break;
            case "ChoiceCourse":
                Is_choiceCourse(req, resp, session);
                break;
            case "choice":
                choiceCourse(req, resp, session);
                break;
            case "selectedCourse":
                Seleced_Course(req, resp, session);
                break;
            case "ExitCourse":
                PreExitCourse(req, resp, session);
                break;
            case "SuerExitCourse":
                SuerExitCourse(req, resp, session);
                break;
            case "FindOwnGrade":
                String sid = (String) session.getAttribute("sid");
                String pageIndex = req.getParameter("pageIndex");
                PageUtils<GradeDto> gradeDtoPageUtils = studentService.FindOwnGrade(sid, Integer.parseInt(pageIndex));
                req.setAttribute("pageUtilsGrade",gradeDtoPageUtils);
                req.getRequestDispatcher("/student/endCourse.jsp").forward(req,resp);

        }
    }

    private void SuerExitCourse(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException {
        String cid = req.getParameter("cid");
        String sid = (String) session.getAttribute("sid");
        try {
            studentService.ExitCouese(cid,sid);

        }catch (RuntimeException e){
            resp.getWriter().write("<script>alert('退选失败');;location.href='/studentServlet.do?flag=ExitCourse&pageIndex=1';</script>");
        }
        resp.getWriter().write("<script>alert('推选成功');;location.href='/studentServlet.do?flag=ExitCourse&pageIndex=1';</script>");
    }

    private void PreExitCourse(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String sid = (String) session.getAttribute("sid");
        String pageIndex = req.getParameter("pageIndex");
        PageUtils<CourseplanDto> coursePageUtils = courseService.FindCourseByStudentid(sid,Integer.parseInt(pageIndex));
        req.setAttribute("PageUtilsexit",coursePageUtils);
        req.getRequestDispatcher("/student/exitSel.jsp").forward(req,resp);
    }

    private void Seleced_Course(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String sid = (String) session.getAttribute("sid");
        String pageIndex = req.getParameter("pageIndex");
        PageUtils<CourseplanDto> coursePageUtils = courseService.FindCourseByStudentid(sid, Integer.parseInt(pageIndex));
        req.setAttribute("pageUtilsPs",coursePageUtils);
        req.getRequestDispatcher("/student/selectedCourse.jsp").forward(req,resp);
    }

    private void choiceCourse(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String cid = req.getParameter("cid");
        String sid = (String) session.getAttribute("sid");
        Result result1 = studentService.addCoursetoSC(cid, sid);
        if (result1.getCode()!=200){
            req.setAttribute("msg", Resultcode.Select_Error.getMess());
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg",Resultcode.System_success.getMess());
            req.getRequestDispatcher("/success.jsp").forward(req,resp);

        }
    }

    private void Is_choiceCourse(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws ServletException, IOException {
        String cids = req.getParameter("cid");
        int cid = Integer.parseInt(cids);
        String sids = (String)session.getAttribute("sid");
        String cname = null;
        Course course = courseService.findClassname(cid);

        //如果返回的為true 説明sc这张表没有 即没有选这么课 判断是否重复
        if (studentService.isChoiced(cids,sids)){

            //判断是否有老师 返回true表示有老师
            if (studentService.CourseIsTeacher(cid)){
                //前端需要 课程名(cname),课程编号(cid),代课教师(tname),教师简介(inroduction)
                Courseplan courseplan = courseService.FindCourse(cid);
                Teacher teacherName = teacherService.findTeacherName(courseplan.getTid());

                cname = course.getCname();
                req.setAttribute("cname",cname);
                req.setAttribute("cid",cid);
                req.setAttribute("tname",teacherName.getTname());
                req.setAttribute("inroduction",teacherName.getIntroduction());
                req.getRequestDispatcher("/student/seling.jsp").forward(req,resp);
            }else {

                req.setAttribute("cid",cid);
                req.setAttribute("cname",course.getCname());
                req.getRequestDispatcher("/student/noseling.jsp").forward(req,resp);
            }
        }else {
            req.setAttribute("msg", Resultcode.Select_OverLaod.getMess());
            req.getRequestDispatcher("/fail.jsp").forward(req,resp);
        }
    }

    private void FindAllCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageIndex = req.getParameter("pageIndex");
        String condition = req.getParameter("condition");
        String type = req.getParameter("type");
        PageUtils pageUtils = new PageUtils();
        pageUtils.setPageIndex(Integer.parseInt(pageIndex));
        pageUtils.setPagesize(5);
        PageUtils<Course> coursePageUtils = studentService.ShowAllStudnetChoiceClass(pageUtils);
        req.setAttribute("pageUtils",coursePageUtils);
        req.setAttribute("type",type);
        req.setAttribute("condition",condition);
        req.getRequestDispatcher("/student/selCourse.jsp").forward(req,resp);
    }

    private Result add_user(HttpServletRequest req) {
        String sid = req.getParameter("sid");
        String sname = req.getParameter("sname");
        String sidcard = req.getParameter("sidcard");
        String ssex = req.getParameter("ssex");
        String spassword = req.getParameter("spassword");
        String sage = req.getParameter("sage");
        String profession = req.getParameter("profession");
        String college = req.getParameter("college");
        String classr = req.getParameter("classr");
        Student student = new Student(sid, sname, sidcard, ssex, spassword, sage, profession, college, classr);

        Result result = studentService.addStudent(student);

        return result;
    }

    private void student_logout(HttpServletResponse resp, HttpSession session) throws IOException {
        session.invalidate(); //session失效
        resp.sendRedirect("login.jsp");
    }

    private void student_login(HttpServletRequest req, HttpServletResponse resp, HttpSession session, String syscode) throws IOException, ServletException {
        String sid = req.getParameter("sid");
        String spassword = req.getParameter("spassword");
        String usercode = req.getParameter("usercode");
        if(syscode.equalsIgnoreCase(usercode)){
            //封对象
            Student s=new Student(sid,spassword);
            //调用登录
            Student studentLogin = studentService.studentLogin(s);
            if(studentLogin!=null){
                //存储登录会话信息
                session.setAttribute("sname",studentLogin.getSname());
                session.setAttribute("sid",studentLogin.getSid());
                //重定向
                resp.sendRedirect("/student/studentFace.jsp");
            }else{
                //存值转发
                req.setAttribute("msg","账号或密码错误！");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }else{
            req.setAttribute("msg","验证码错误！");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
